package com.web.test.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by St01 on 2017-9-25.
 */
public class MyFilter implements Filter {

    String encode;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        encode = filterConfig.getServletContext().getInitParameter("encoding");

        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("filter");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String username = request.getParameter("username");

        if (username != null && !username.equals("")  && username.length() > 0 && username.length() < 16 && encode.equals("utf-8")){

            filterChain.doFilter(servletRequest,servletResponse);
            response.getWriter().write("姓名为"+username+"成功通过过滤器了");
        }else {

            request.setAttribute("errorMsg","验证不通过");
            request.getRequestDispatcher("filter_index.jsp").forward(request,response);
        }



    }

    @Override
    public void destroy() {

        System.out.println("destroy");

    }
}
